<?php
/**
 * Manage user asks.
 *
 * @package    letsManager
 * @subpackage letsUserAsk
 * @author     Jerome Fouilloy
 * @version    SVN: $Rev$
 */
class letsUserAskActions extends sfActions
{
  /**
   * Form new user ask
   */
  public function executeNew(sfWebRequest $request)
  {
    $this->linkCancel = $this->getUser()->getCurrentReferer();
    $this->member_id = $this->getUserIdModified($request);
    $canAddAskOrOffer = LetsManagerRights::canAddAskOrOffer($this->member_id,$this->getUser()->getAssociationId());
    if(!$canAddAskOrOffer)
    {
      $this->getUser()->setFlash('notice',"Vous avez atteint la limite d'offres et demandes");
      $this->redirect($this->linkCancel);
    }
    $this->form = new LetsUserAskForm(null,array(
			'context'=> $this->getContext()
    ));

  }
  /**
   * Creating new user ask
   */
  public function executeCreate(sfWebRequest $request)
  {
    $this->form = new LetsUserAskForm(null,array(
		'context'=> $this->getContext()
    ));
    $this->processForm($request, $this->form, new LetsUserAsk());
    $this->linkCancel = $this->getUser()->getCurrentReferer();
    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $id = $request->getParameter('id');
    $this->forward404Unless($userAsk = LetsUserAskTable::getInstance()->find($id));
    $this->checkRightEditAsk($userAsk);
    $this->form = new LetsUserAskForm($userAsk,array(
			'context'=> $this->getContext()
    ));
    $this->linkCancel = $this->getUser()->getCurrentReferer();
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
    $id = $request->getParameter('id');
    $this->forward404Unless($userAsk = LetsUserAskTable::getInstance()->find($id));
    $this->checkRightEditAsk($userAsk);
    	
    $this->form = new LetsUserAskForm($userAsk,array(
      'context'=> $this->getContext()
    ));
    $this->processForm($request, $this->form, $userAsk);
    $this->linkCancel = $this->getUser()->getCurrentReferer();
    $this->setTemplate('edit');
  }

  public function executeIndex(sfWebRequest $request)
  {
    $asso_id = $this->getUser()->getAssociationId();
    $page = $request->getParameter('page', 1);
    $this->keySearch = $request->getParameter('query',null);
     
    $this->category_id = $request->getParameter('category_id', -1);
    $this->asksPager = LetsUserAskTable::getAsksPager($asso_id,$this->category_id,$page,$this->keySearch);
    $this->searchForm = new LetsCategoryFilterForm(null,array('category_id'=>$this->category_id));
    if($this->keySearch != null)
    {
      $this->searchForm->setDefault('query',$this->keySearch);
    }
    $this->canManageAsks = $this->hasRightManageAsks();

    $this->getUser()->setCurrentReferer('@lets_user_asks_list');
  }

  public function executeDelete(sfWebRequest $request)
  {
    // 	$request->checkCSRFProtection();
    $id = $request->getParameter('id');
    $userAsk = LetsUserAskTable::getInstance()->find($id);
    $this->forward404Unless($userAsk);
    // suppression d'une demande d'un autre user sans droit manager on refuse
    $this->checkRightEditAsk($userAsk);

    $userAsk->delete();
    $this->redirect($this->getUser()->getCurrentReferer());
  }
  public function executeRenew(sfWebRequest $request)
  {
    $id = $request->getParameter('id',-1);
    $userAsk = LetsUserAskTable::getInstance()->find($id);
    $this->checkRightEditAsk($userAsk);
    if($userAsk != null)
    {
      //$timeExpire = strtotime($userAsk->getDateExpiration());
      $days =0; $years =0;
      if($userAsk->isNeverExpire())
      {
        $years =1;
        $userAsk->setDateMailExpiration(null);
      }
      else{
        $days = $userAsk->getPeriodExpiration();
      }
      //$newExpiration  = mktime(0, 0, 1,date("m",$timeExpire),date("d",$timeExpire)+$days,date("Y",$timeExpire)+$years);
      $newExpiration  = mktime(0, 0, 1,date("m"),date("d")+$days,date("Y")+$years);
      $userAsk->setDateExpiration(date('Y-m-d',$newExpiration));

      $userAsk->save();
    }
    $this->redirect($this->getUser()->getCurrentReferer());
  }
  protected function checkRightEditAsk(LetsUserAsk $userAsk)
  {
    if($userAsk->getMemberId() != $this->getUser()->getUserId() &&
    !$this->hasRightManageAsks() )
    {
      $this->redirect('@error_credentials');
    }
  }
  protected function hasRightManageAsks()
  {
    return $this->getUser()->hasCredential(LetsManagerRights::MANAGE_ASKS_OFFERS_OTHERS);
  }
  /**
   * Extract user id from request (if current user edit member)
   * or from the session if not manager
   */
  protected function getUserIdModified(sfWebRequest $request)
  {
    $idReturned = $request->getParameter('member_id',-1);

    if( !$this->hasRightManageAsks() || $idReturned == -1)
    {
      $idReturned = $this->getUser()->getUserId();
    }
    return $idReturned;
  }
  protected function processForm(sfWebRequest $request, sfForm $form,LetsUserAsk  $userAsk)
  {
    $form->bind($request->getParameter($form->getName()));
    if ($form->isValid())
    {
      $values = $form->getValues();
      $userAsk->setName($values['name']);
      $userAsk->setCategoryId($values['category_id']);

      if($userAsk->isNew())
      {
        $userAsk->setPeriodExpiration($values['delay_expiration']);
        $userAsk->setMemberId($this->getUserIdModified($request));
         
        // expire auto au bout de 1 an mais avec confirmation du membre que la demande n'est plus valable
        if($userAsk->isNeverExpire())
        {
          $userAsk->setAskBeforeDelete(true);
          $nextyear  = mktime(0, 0, 1,date("m"),date("d"),date("Y")+1);
          $userAsk->setDateExpiration(date('Y-m-d',$nextyear));
        }
        else{
          $userAsk->setAskBeforeDelete(false);
          $expiration  = mktime(0, 0, 1,date("m"),date("d") + $userAsk->getPeriodExpiration(),date("Y"));
          $userAsk->setDateExpiration(date('Y-m-d',$expiration));
        }
      }
      $userAsk->save();
      $this->redirect($this->getUser()->getCurrentReferer());
    }
  }
}